import { createSlice } from "@reduxjs/toolkit";

import categoryApi from "@/api/category";

const categorySlice = createSlice({
  name: "category",
  initialState: {
    category1Id: "",
    category2Id: "",
    category3Id: "",
    cateGory1List: [],
    cateGory2List: [],
    cateGory3List: [],
  },
  reducers: {
    // 同步代码对数据进行修改
    // 获取一级分类的列表数据
    getCategory1List: (state, action) => {
      state.cateGory1List = action.payload;
    },
    // 修改1级分类id
    changeCategory1Id: (state, { payload }) => {
      state.category1Id = payload;
    },
    getCategory2List: (state, action) => {
      state.cateGory2List = action.payload;
    },
    // 修改2级分类id
    changeCategory2Id: (state, { payload }) => {
      state.category2Id = payload;
      // console.log(state.category2Id)
    },
    // 三级分类数据
    getCategory3List: (state, action) => {
        // console.log(action.payload)
        state.cateGory3List = action.payload;
    },
    // 修改2级分类id
    changeCategory3Id: (state, { payload }) => {
      state.category3Id = payload;
      // console.log(state.category3Id)
    },
  },
});

// 向外暴露action函数
export const { getCategory1List, changeCategory1Id, getCategory2List ,changeCategory2Id,getCategory3List,changeCategory3Id} =
  categorySlice.actions;

// 书写异步代码

// 获取一级分类的数据
export const asyncCategory1List = () => {
  return async (dispatch: any) => {
    // 发送ajax请求
    try {
      let result = await categoryApi.getCategory1();
      // console.log(result,'slice切片的数据')
           // 简化代码-1Id和2id可以将请求回来得数据直接存储3Id使用inChange
    // dispatch(getCategory2List(result,category2Id))
      dispatch(getCategory1List(result));
    } catch (error) {
      return Promise.reject(error);
    }
  };
};

// 获取二级分类的数据
export const asyncCategory2List = (category1Id: number) => {
  return async (dispatch: any) => {
    try {
      let result = await categoryApi.getCategory2(category1Id);
      dispatch(getCategory2List(result));
    } catch (error) {
        return Promise.reject(error)
    }
  };
};

// 获取三级分类的数据
export const asyncCategory3List = (category2Id: number) => {
  return async (dispatch: any) => {
    try {
      let result = await categoryApi.getCategory3(category2Id);
    //   console.log(result,'三级分类数据')

      dispatch(getCategory3List(result));
    } catch (error) {
        return Promise.reject(error)
    }
  };
};

// 向外暴露reducer函数
export default categorySlice.reducer;
